package com.cnap.multiclouldmgmt.service.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.cnap.multiclouldmgmt.model.alg.*;
import com.cnap.multiclouldmgmt.service.AlgorithmService;
import com.cnap.multiclouldmgmt.util.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

/**
 * <类文件描述>
 *
 * @author xc
 **/
@Service
public class AlgorithmServiceImpl implements AlgorithmService {

    private static final Logger LOGGER = LoggerFactory.getLogger(AlgorithmServiceImpl.class);
    private static final String ALG_MGMT_URL = "http://cnap-algorithm-svc.default.svc.cluster.local:8808";
    private static final String CPU_PATH = "/cpu_thresh";
    private static final String RES_TIME_PATH = "/response_time_thresh";
    private static final String GPU_TEMPERATURE_PATH = "/gpu_temperature_thresh";
    private static final String HEALTH_VALUE_PATH = "/health_value";
    private static final String ROOT_CAUSE_PATH = "/alarm_root_cause";


    @Override
    public ResponseForCPU getCPUThresh(RequestForCPU request) {
        String url = ALG_MGMT_URL + CPU_PATH;
        String paramStr = JsonUtil.objectToJsonStr(request);
        return post(url, paramStr, ResponseForCPU.class);
    }

    @Override
    public ResponseForResTime getResTimeThresh(RequestForResTime request) {
        String url = ALG_MGMT_URL + RES_TIME_PATH;
        String paramStr = JsonUtil.objectToJsonStr(request);
        return post(url, paramStr, ResponseForResTime.class);
    }

    @Override
    public ResponseForGPUTem getGPUTemThresh(RequestForGPUTem request) {
        String url = ALG_MGMT_URL + GPU_TEMPERATURE_PATH;
        String paramStr = JsonUtil.objectToJsonStr(request);
        return post(url, paramStr, ResponseForGPUTem.class);
    }

    private <T> T post(String url, String paramStr, Class<T> cls) {
        HttpResponse response = HttpRequest.post(url).body(paramStr).execute();
        if (!response.isOk()) {
            LOGGER.error("[alg]: can't get response from algorithm system, url={}, param={}", url, paramStr);
            return null;
        }
        return JsonUtil.jsonStrToObject(response.body(), cls);
    }

    @Override
    public ResponseForHealth calHealthValue(RequestForHealth request) {
        String url = ALG_MGMT_URL + HEALTH_VALUE_PATH;
        String paramStr = JsonUtil.objectToJsonStr(request);
        return post(url, paramStr, ResponseForHealth.class);
    }

    @Override
    public ResponseForCause calRootCause(RequestForCause request) {
        String url = ALG_MGMT_URL + ROOT_CAUSE_PATH;
        String paramStr = JsonUtil.objectToJsonStr(request);
        return post(url, paramStr, ResponseForCause.class);
    }
}
